//
//  SearchView.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/10/10.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit

class SearchView: UIView, UITextFieldDelegate {
    
    // 文字编辑框右边约束
    @IBOutlet weak var textFieldRightCons: NSLayoutConstraint!
    // 文字编辑框
    @IBOutlet weak var textField: UITextField!
    // 取消按钮
    @IBOutlet weak var cancelButton: UIButton!
    
   
    class func searchView() -> SearchView {
        
        return NSBundle.mainBundle().loadNibNamed("SearchView", owner: nil, options: nil).last as! SearchView
    }
    
    override func awakeFromNib() {
        
        // 设置文字输入框代理
        textField.delegate = self
        
        // 设置输入框搜索图标
        let leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        leftView.size = CGSizeMake(height, height)
        leftView.contentMode = UIViewContentMode.Center
        
        textField.leftView = leftView
        textField.leftViewMode = UITextFieldViewMode.Always
        // 设置编辑删除按钮
        textField.clearButtonMode = UITextFieldViewMode.Always
        
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        printLog("搜索文本框")
        
        // 调整右边距约束
        self.textFieldRightCons.constant = self.cancelButton.width
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 重新排版布局
            self.layoutIfNeeded()
        }
    }
    
    @IBAction func cancelButtonClick(sender: UIButton) {
        
        // 退出编辑
        endEditing(true)
        
        self.textFieldRightCons.constant = 0
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.layoutIfNeeded()
        }
    }
    

}
